package com.example.blogback.service.impl;

import com.example.blogback.entity.User;
import com.example.blogback.mapper.UserMapper;
import com.example.blogback.service.UserService;
import com.example.blogback.utils.RedisUtils;
import com.example.blogback.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private SmsUtils smsUtils;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info(passwordEncoder.encode("123456"));
        User user = findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        List<SimpleGrantedAuthority> authorities = user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .map(permission -> new SimpleGrantedAuthority(permission.getName()))
                .collect(Collectors.toList());

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getStatus() == 1,
                true,
                true,
                true,
                authorities
        );
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public boolean validatePassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    @Override
    public void sendResetPasswordCode(String username) {
        User user = findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        if (user.getPhone() == null || user.getPhone().isEmpty()) {
            throw new RuntimeException("用户未绑定手机号");
        }

        // 生成6位随机验证码
        String code = String.format("%06d", new Random().nextInt(1000000));

        // 将验证码保存到Redis，设置5分钟过期
        String redisKey = "reset_password_code:" + username;
        redisUtils.set(redisKey, code, 5, TimeUnit.MINUTES);

        // 发送验证码短信
        smsUtils.sendVerificationCode(user.getPhone(), code);
    }

    @Override
    public void resetPassword(String username, String code, String newPassword) {
        User user = findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 验证验证码
        String redisKey = "reset_password_code:" + username;
        String savedCode = (String) redisUtils.get(redisKey);
        if (savedCode == null || !savedCode.equals(code)) {
            throw new RuntimeException("验证码无效或已过期");
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(newPassword));
        userMapper.updatePassword(user);

        // 删除验证码
        redisUtils.delete(redisKey);
    }

    @Override
    public boolean hasPermission(String username, String permission) {
        User user = findByUsername(username);
        if (user == null) {
            return false;
        }

        return user.getRoles().stream()
                .flatMap(role -> role.getPermissions().stream())
                .anyMatch(p -> p.getName().equals(permission));
    }
}